package com.chuangke.file.util;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.tika.Tika;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;

public class TikaUtil {

    public static final Logger logger = LoggerFactory.getLogger(TikaUtil.class);

    public static void main(String[] args) {
        File file = new File("E:\\d.pptx");
        System.out.println(getMimeType(file));
        System.out.println("----------------------------------------------");
        String content = getContent(file);
        System.out.println("----------------------------------------------");
        System.out.println(content);
    }


    public static String getMimeType(File file) {
        Tika tika = new Tika();
        try {
            return tika.detect(file);
        } catch (Throwable e) {
            logger.error(e.getMessage());
        }
        return "";
    }

    public static String getMimeType(byte[] content) {
        Tika tika = new Tika();
        try {
            return tika.detect(content);
        } catch (Throwable e) {
            logger.error(e.getMessage());
        }
        return "";
    }

    public static String getContent(File file) {
        Tika tika = new Tika();
        try {
            return tika.parseToString(file);
        } catch (Throwable e) {
            logger.error(e.getMessage());
        }
        return "";
    }

    public static String getContent(byte[] content) {
        if (ArrayUtils.isEmpty(content)) {
            return "";
        }

        Tika tika = new Tika();
        try {
            return tika.parseToString(new BufferedInputStream(new ByteArrayInputStream(content)));
        } catch (Throwable e) {
            logger.error(e.getMessage());
        }
        return "";
    }
}
